﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Web;
using Mysoft.ModelAnalysis.Utility;
using 检查页面开放.Models;

namespace 检查页面开放.Business
{


    public class GetAppApi
    {
        public List<Models.MethodInfo> List { get; set; }

        public GetAppApi()
        {
            List = new List<Models.MethodInfo>();
        }

        public List<Models.MethodInfo> GetApi()
        {
            List<AppDataSource> pathList = DataSourceHelp.GetModelDlls(HttpContext.Current.Server.MapPath(PathConst.AppDataSouce));
            foreach (var path in pathList)
            {
                List.AddRange(GetDllApi(path));
            }

            return List;
        }

        public List<Models.MethodInfo> GetDllApi(AppDataSource source)
        {
            var dllPath = source.Path;
            MdDocGenerator.Client.MdDocClient mdDocClient = new MdDocGenerator.Client.MdDocClient();
            List<MdDocGenerator.Client.Model.MyMethodInfo> myMethodInfos = mdDocClient.QueryMethodRemark(new List<string> { dllPath });

            List<Models.MethodInfo> methodInfos = new List<Models.MethodInfo>();
            FileInfo info = new FileInfo(dllPath);
            Assembly ass = Assembly.LoadFrom(dllPath);
            List<Type> typeList = ass.GetTypes().ToList();
            typeList.RemoveAll(p => (p.BaseType == null || p.BaseType.Name != "AppService"));
            typeList.RemoveAll(t => t.Name.EndsWith("PubAppService"));
            foreach (var c in typeList)
            {
                var allMethod = c.GetMethods().Where(t => t.IsPrivate == false);
                foreach (var m in allMethod)
                {
                    if (m.DeclaringType.FullName != c.FullName)
                    {
                        continue;
                    }
                    try
                    {
                        if (m.GetCustomAttributes() != null && m.GetCustomAttributes().Any(t => t.GetType() != null && t.GetType().Name == "ForbidHttpAttribute") == false)
                        {
                            AddMethod(source, myMethodInfos, methodInfos, info, c, m);
                        }
                    }
                    catch (Exception)
                    {
                        AddMethod(source, myMethodInfos, methodInfos, info, c, m);
                    }

                }
            }
            return methodInfos;
        }

        private void AddMethod(AppDataSource source, List<MdDocGenerator.Client.Model.MyMethodInfo> myMethodInfos, List<Models.MethodInfo> methodInfos, FileInfo info, Type c, System.Reflection.MethodInfo m)
        {
            MdDocGenerator.Client.Model.MyMethodInfo remark = GetMethodRemark(myMethodInfos, m);
            methodInfos.Add(new Models.MethodInfo
            {
                DllName = info.Name,
                ModelName = source.Name,
                ClassName = c.Name,
                ClassFullName = m.DeclaringType.FullName,
                MethodName = m.Name,
                MethodRemark = remark == null ? "" : remark.Remark,
                Params = m.GetParameters().ParameterInfo2My()
            });
        }

        private MdDocGenerator.Client.Model.MyMethodInfo GetMethodRemark(List<MdDocGenerator.Client.Model.MyMethodInfo> myMethodInfos, System.Reflection.MethodInfo m)
        {
            var fullName = $"{m.DeclaringType.FullName}.{m.Name}";
            var remark = myMethodInfos.First(t => t.MethodFullName == fullName);
            if (remark == null)
            {
                throw new BusinessLogicException(fullName + "注释不匹配");
            }

            return remark;
        }

        public List<Models.MethodInfo> GetInterFaceApi()
        {
            List<string> pathList = DataSourceHelp.GetItems(HttpContext.Current.Server.MapPath("~/App_Data/InterFaceDataSouce.xml"));
            foreach (var path in pathList)
            {
                List.AddRange(GetPublicSerivceApi(path));
            }
            return List;
        }

        /// <summary>
        /// 获取publicservice
        /// </summary>
        /// <param name="dllPath"></param>
        /// <returns></returns>
        public List<Models.MethodInfo> GetPublicSerivceApi(string dllPath, string modelName = "")
        {
            List<Models.MethodInfo> methodInfos = new List<Models.MethodInfo>();
            if (File.Exists(dllPath) == false)
            {
                return methodInfos;
            }
            FileInfo info = new FileInfo(dllPath);
            Assembly ass = Assembly.LoadFrom(dllPath);
            List<Type> typeList = ass.GetTypes().ToList();
            MdDocGenerator.Client.MdDocClient mdDocClient = new MdDocGenerator.Client.MdDocClient();
            List<MdDocGenerator.Client.Model.MyMethodInfo> myMethodInfos = mdDocClient.QueryMethodRemark(new List<string> { dllPath });

            typeList.RemoveAll(p => p.GetInterface("IPublicService") == null);
            foreach (var c in typeList)
            {

                var allMethod = c.GetMethods().Where(t => t.IsPrivate == false);
                foreach (var m in allMethod)
                {
                    MdDocGenerator.Client.Model.MyMethodInfo remark = GetMethodRemark(myMethodInfos, m);
                    methodInfos.Add(new Models.MethodInfo
                    {
                        DllName = info.Name,
                        ClassName = c.Name,
                        ModelName = modelName,
                        ClassFullName = m.DeclaringType.FullName,
                        MethodName = m.Name,
                        IsPublic = true,
                        IsOpen = m.GetCustomAttributes().Any(t => t.GetType().Name == "ExportApiAttribute"),
                        MethodRemark = remark.Remark,
                        Params = m.GetParameters().ParameterInfo2My()
                    });
                }
            }
            return methodInfos;
        }

        public static List<MethodDiff> CompareDll(List<Models.MethodInfo> methodInfos1, List<Models.MethodInfo> methodInfos2)
        {
            if (methodInfos1 == null)
            {
                throw new ArgumentException(nameof(methodInfos1));
            }
            if (methodInfos2 == null)
            {
                throw new ArgumentException(nameof(methodInfos2));
            }

            List<MethodDiff> compareDiffs = new List<MethodDiff>();
            foreach (Models.MethodInfo methodInfo1 in methodInfos1)
            {
                MethodDiff compareDiff = new MethodDiff();
                compareDiff.Method1 = methodInfo1;
                var methodInfo2 = methodInfos2.FirstOrDefault(t => t.ClassName == methodInfo1.ClassName && t.MethodName == methodInfo1.MethodName);
                //判断是否存在
                if (methodInfo2 == null)
                {
                    compareDiff.IsDiff = true;
                    compareDiff.DiffType = DiffEnum.Deleted;
                    compareDiff.Method2 = new Models.MethodInfo();
                    compareDiffs.Add(compareDiff);
                    continue;
                }
                compareDiff.Method2 = methodInfo2;
                //"a".ToString().st
                //判断参数个数、类型是否调整
                if (methodInfo1.Params.CompareParas(methodInfo2.Params) == false)
                {
                    compareDiff.IsDiff = true;
                    compareDiff.DiffType = DiffEnum.Params;
                    compareDiffs.Add(compareDiff);
                    continue;
                }
                //判断内容行数是否调整
                //判断注释是否调整
                if (methodInfo1.MethodRemark != methodInfo2.MethodRemark)
                {
                    compareDiff.IsDiff = true;
                    compareDiff.DiffType = DiffEnum.Remarks;
                    compareDiffs.Add(compareDiff);
                    continue;
                }
            }
            foreach (var methodInfo2 in methodInfos2)
            {
                MethodDiff compareDiff = new MethodDiff();
                compareDiff.Method2 = methodInfo2;
                var methodInfo1 = methodInfos1.FirstOrDefault(t => t.ClassName == methodInfo2.ClassName && t.MethodName == methodInfo2.MethodName);
                //判断是否存在
                if (methodInfo1 == null)
                {
                    compareDiff.Method1 = new Models.MethodInfo();
                    compareDiff.IsDiff = true;
                    compareDiff.DiffType = DiffEnum.Add;
                    compareDiffs.Add(compareDiff);
                    continue;
                }
            }
            return compareDiffs;
        }

        /// <summary>
        /// 获取所有业务模块的方法
        /// </summary>
        /// <returns></returns>
        public List<Model> GetModels(List<AppDataSource> appDataSource)
        {
            List<Model> modelList = new List<Model>();
            //获取dll的物理路径
            foreach (var source in appDataSource)
            {
                List<Models.MethodInfo> appList = GetDllApi(source);
                appList.AddRange(GetPublicSerivceApi(GetInterfaceDllName(source.Path), source.Name));
                modelList.Add(new Model
                {
                    Name = source.Name,
                    MethodList = appList
                });
            }
            return modelList;
        }

        private string GetInterfaceDllName(string dll)
        {
            //Mysoft.PubPlatform.ProjectOverview.Interfaces.dll
            //PublicServices
            var dllSplit = dll.Split(new char[] { '.' }).ToList();
            dllSplit.Insert(dllSplit.Count - 1, "Interfaces");
            string interfaceDllName = string.Join(".", dllSplit);
            //兼容主数据
            if (File.Exists(interfaceDllName) == false)
            {
                dllSplit = dll.Split(new char[] { '.' }).ToList();
                dllSplit.Insert(dllSplit.Count - 1, "PublicServices");
                interfaceDllName = string.Join(".", dllSplit); 
            }
            //兼容投资收益
            if (File.Exists(interfaceDllName) == false)
            {
                dllSplit = dll.Split(new char[] { '.' }).ToList();
                dllSplit.Insert(dllSplit.Count - 1, "Interface");
                interfaceDllName = string.Join(".", dllSplit);
            }
            return interfaceDllName;
        }
    }
    public static class Object2Extension
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="paras"></param>
        /// <param name="compares"></param>
        /// <remarks>返回true表示一直</remarks>
        /// <returns></returns>
        public static bool CompareParas(this List<MyParameterInfo> paras, List<MyParameterInfo> compares)
        {
            if (paras == null && compares == null)
            {
                return true;
            }

            if ((paras == null && compares != null) || (paras != null && compares == null) || paras.Count != compares.Count)
            {
                return false;
            }
            for (int i = 0; i < paras.Count; i++)
            {
                if (paras[i].TypeName != compares[i].TypeName)
                {
                    return false;
                }
            }

            return true;
        }

        public static List<MyParameterInfo> ParameterInfo2My(this ParameterInfo[] paras)
        {
            List<MyParameterInfo> myParameterInfos = new List<MyParameterInfo>();
            if (paras == null || paras.Any() == false)
            {
                return myParameterInfos;
            }
            foreach (var para in paras)
            {
                MyParameterInfo myParameterInfo = new MyParameterInfo();
                myParameterInfo.TypeName = para.ParameterType.FullName;
                myParameterInfos.Add(myParameterInfo);
            }
            return myParameterInfos;
        }

    }
}